import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router';
import { useLoginUserStore } from '../store';

const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    name: 'MainForm',
    component: () => import('../views/layout/MainForm.vue'),
    meta: { requiresAuth: true },
    children: [
      {
        path: '/:catchAll(.*)',
        name: 'NotFound',
        component: () => import('../views/error/404.vue')
      }
    ]
  },
  //登录页面静态
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/Login/LoginForm.vue'),
    meta: { requiresAuth: false },
  },
  //其他路由配置

];

const router = createRouter({
  history: createWebHistory(),
  routes,
});

// 路由守卫
router.beforeEach((to, from, next) => {
  // 使用 Pinia store
  const loginUserStore = useLoginUserStore(); // 创建 userStore 实例
  const isAuthenticated = loginUserStore.isAuthenticated;
  if (isAuthenticated && loginUserStore.currentUser) {
    loginUserStore.dynamicRoutes();
  }

  if (to.meta.requiresAuth && !isAuthenticated) {
    next({ name: 'Login' });
  } else if (to.path === '/login' && isAuthenticated) {
    next({ name: 'MainForm' });
  }
  else {
    next();
  }
});

export default router;